<template>
  <div
    class="login-container w-screen h-screen bg-slate-600 flex items-center justify-end"
    :style="style"
  >
    <Form
      class="w-[428px] px-11 py-[60px] mr-[346px] rounded-md bg-[#ffffff21]"
      ref="formRef"
      :rules="rules"
      :model="formState"
      layout="vertical"
      hideRequiredMark
    >
      <div class="font-semibold text-3xl text-center mx-auto mb-5 text-white">
        <div>{{ commonStore.sysName }}</div>
      </div>
      <FormItem label="登录" name="username">
        <Input
          v-model:value="formState.username"
          size="large"
          placeholder="账号"
        >
          <template #prefix><UserOutlined /></template>
        </Input>
      </FormItem>
      <FormItem name="password">
        <InputPassword
          v-model:value="formState.password"
          size="large"
          placeholder="密码"
          @keyup.enter="handleLogin"
        >
          <template #prefix><LockOutlined /></template>
        </InputPassword>
      </FormItem>
      <FormItem name="code" v-if="needCaptcha">
        <Flex>
          <Input
            v-model:value="formState.code"
            size="large"
            placeholder="验证码"
            @keyup.enter="handleLogin"
          />
          <img
            class="h-10 ml-2 rounded-sm"
            :src="captcha"
            @click="refreshCode"
          />
        </Flex>
      </FormItem>
      <FormItem>
        <Checkbox v-model:checked="formState.rememberMe">记住密码</Checkbox>
      </FormItem>
      <FormItem>
        <Button
          class="w-full"
          size="large"
          type="primary"
          @click="handleLogin"
          :loading="loading"
          >登录</Button
        >
      </FormItem>
    </Form>

    <div class="text-white text-sm fixed bottom-4 left-1/2 -translate-x-1/2">
      <span>版权所有：武汉博远减灾科技股份有限公司</span>
      <span>软件版本：V1.0</span>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { CSSProperties, computed, onMounted, ref } from 'vue';
import { useCommonStore, useUserStore } from '@/stores/modules';
import { LockOutlined, UserOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Checkbox,
  Flex,
  Form,
  FormItem,
  Input,
  InputPassword,
} from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import Cookie from 'js-cookie';
import { useRequest } from 'vue-request';
import { useRoute, useRouter } from 'vue-router';
import { fetchCodeImageApi } from '@/api/login';

const USER_NAME_KEY = 'ACCOUNT';
const PASSWORD_KEY = 'ACCOUNT_SECRET';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const commonStore = useCommonStore();
interface LoginState {
  username: string;
  password: string;
  rememberMe: boolean;
  code: string;
  uuid: string;
}

const formRef = ref<FormInstance>();
const formState = ref<LoginState>({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
});
onMounted(() => {
  const username = Cookie.get(USER_NAME_KEY);
  const password = Cookie.get(PASSWORD_KEY);
  if (username && password) {
    formState.value = {
      ...formState.value,
      username,
      password: atob(password),
      rememberMe: true,
    };
  }
});

const rules: Record<keyof Omit<LoginState, 'rememberMe' | 'uuid'>, Rule[]> = {
  username: [{ trigger: 'blur', required: true, message: '请输入用户名' }],
  password: [{ trigger: 'blur', required: true, message: '请输入密码' }],
  code: [{ trigger: 'blur', required: true, message: '请输入验证码' }],
};

const { run: login, loading } = useRequest(userStore.login, {
  manual: true,
  onSuccess() {
    router.push({ path: (route.query.redirect as string) || '/' });
  },
});

const handleLogin = async () => {
  const result = await formRef.value?.validate();

  if (formState.value.rememberMe) {
    const { username, password } = formState.value;
    Cookie.set(USER_NAME_KEY, username);
    Cookie.set(PASSWORD_KEY, btoa(password));
  }
  if (!result) return;
  login(formState.value);
};

const needCaptcha = ref(false);
const captcha = ref('');

const refreshCode = () => {
  fetchCodeImageApi().then((res) => {
    needCaptcha.value = (res as any).captchaOnOff ?? true;
    if (needCaptcha.value) {
      captcha.value = `data:image/gif;base64,${(res as any).img}`;
      formState.value.uuid = (res as any).uuid;
    }
  });
};

refreshCode();

const style = computed<CSSProperties>(() => {
  return {
    backgroundImage: `url(${commonStore.loginBgUrl})`,
  };
});
</script>

<style lang="scss" scoped>
.login-container {
  background-repeat: no-repeat;
  background-size: cover;
}
form {
  box-shadow: 0 0 40px #08071099;
  backdrop-filter: blur(5px);
}
</style>
